package net.sevear.chaos.douban.shuo
{
	import de.popforge.utils.SprintfUtil;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	public class DBShuoLike extends EventDispatcher
	{
		private var _shuoID:int;
		private var isSendingRequest:Boolean = false;
		private var shuoloader:URLLoader;
		private var _ck:String;
		
		public function DBShuoLike(ck:String)
		{
			super(null);
			_ck = ck;	
			shuoloader = new URLLoader();
			shuoloader.addEventListener(Event.COMPLETE,onShuoLikeComplete);
			shuoloader.addEventListener(IOErrorEvent.IO_ERROR,onShuoLikeIOError);
		}
		
		public function likeDouBanShuo(shuoID:int):void{
			if(shuoID==_shuoID && isSendingRequest) return ;
			else{
				_shuoID = shuoID;
				try{
					shuoloader.close();
				}catch(e:Error){
					
				}
				var rst:URLRequest = new URLRequest(SprintfUtil.sprintf("http://shuo.douban.com/api/statuses/%d/like",shuoID));
				rst.method = URLRequestMethod.POST;
				rst.requestHeaders.push(new URLRequestHeader("Referer","http://shuo.douban.com/"));
				
				var vars:URLVariables = new URLVariables();
				vars.ck = _ck;
				rst.data = vars;
				
				isSendingRequest = true;
				shuoloader.load(rst);
			}
		}
		
		private function onShuoLikeComplete(e:Event):void{
			isSendingRequest = false;
			dispatchEvent(new DBShuoEvent(DBShuoEvent.LIKE_SHUO_SUCCESSFULLY,_shuoID));
		}
		
		private function onShuoLikeIOError(e:IOErrorEvent):void{
			isSendingRequest = false;
		}
	}
}